<?
class Localization {

	function Localization() {
		global $dsfm_lang;

		if(isset($dsfm_lang)){
			$_SESSION['dsfm_lang'] = $dsfm_lang;
		}

		if(!isset($_SESSION['dsfm_lang'])){
			$_SESSION['dsfm_lang'] = "en";
		}
	}

	public static function get_variable(){

		$var = "";

		foreach($_GET as $k => $v){
			if($k == "dsfm_uri") continue;
			if($k == "dsfm_lang") continue;

			$var .= "&".$k."=".$v;
		}

		return $var;
	}

	public static function load($lang = ""){

		if($lang == ""){
			$dsfm_lang = $_SESSION['dsfm_lang'];
		}else{
			$dsfm_lang = $lang;
		}

		$words = array();

		$fp = fopen( MOD.'/localization/lang.'.$dsfm_lang, 'r');
		$all = "";

		while ($line = fgets ($fp)) {
			$all.=$line;
		}
		fclose($fp);

		$word = explode("#",$all);
		for($i = 1; $i < count($word); $i++){
			$a = explode("=>",$word[$i]);
			$words[$a[0]] = trim($a[1]);
		}

		return $words;
	}

	public function save($data, $lang){

		$txt = "";

		foreach($data as $key => $value){
			$txt .= "#".$key."=>".$value."\r\n";
		}

		$fp = fopen( MOD.'/localization/lang.'.$lang, 'w');

		fwrite($fp,$txt);
		fclose($fp);
	}

	public function add($key, $word, $lang){

		$fp = fopen( MOD.'/localization/lang.'.$lang, 'a+');

		$txt = "#".$key."=>".$word."\r\n";

		fwrite($fp, $txt);
		fclose($fp);
	}

	public function remove($key, $lang){

		$all = $this->load($lang);

		$txt = "";

		foreach($all as $k => $v){
			if($k != $key){
				$txt .= "#".$k."=>".$v."\r\n";
			}
		}

		$fp = fopen( MOD.'/localization/lang.'.$lang, 'w');

		fwrite($fp,$txt);
		fclose($fp);
	}

	public static function data($data, $field = "", $lang = ""){

		if($lang == ""){
			$dsfm_lang = $_SESSION['dsfm_lang'];
		}else{
			$dsfm_lang = $lang;
		}

		if(is_array($field)){
			foreach($data as $k => $row){
				foreach($row as $col => $v){
					foreach($field as $key => $value){
						if($value."_".$dsfm_lang == $col){
							$data[$k][$value] = $v;
						}
					}
				}
			}
		}elseif($field != ""){
			foreach($data as $k => $row){
				foreach($row as $col => $v){
					if($field."_".$dsfm_lang == $col){
						$data[$k][$field] = $v;
					}
				}
			}
		}

		return $data;
	}

	public static function object($arr, $field = "", $lang = ""){

		if($lang == ""){
			$dsfm_lang = $_SESSION['dsfm_lang'];
		}else{
			$dsfm_lang = $lang;
		}

		if(is_array($field)){
			foreach($arr as $k => $v){
				foreach($field as $key => $value){
					if($value."_".$dsfm_lang == $k){
						$arr[$value] = $v;
					}
				}
			}
		}elseif($field != ""){
			foreach($arr as $k => $v){
				if($field."_".$dsfm_lang == $k){
					$arr[$field] = $v;
				}
			}
		}
		return $arr;
	}
}
?>